package com.yiwan.app.preventionsis.ui;


import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.drawable.AnimationDrawable;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.widget.ImageView;
import android.widget.Toast;
import com.app.tianwan.tianwanframe.ui.FrameActivity;
import com.app.tianwan.tianwanframe.utils.LogUtil;
import com.app.tianwan.tianwanframe.utils.PreferencesUtils;
import com.app.tianwan.tianwanframe.widget.CustomProgressDialog;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengRegistrar;
import com.yiwan.app.preventionsis.R;
import com.yiwan.app.preventionsis.config.GlobalCfg;
import com.yiwan.app.preventionsis.config.ImageResManager;
import com.yiwan.app.preventionsis.util.AppConfig;
import com.yiwan.app.preventionsis.util.UpdateManager;
import com.yiwan.app.preventionsis.view.FloatImageView;
import com.yiwan.app.preventionsis.view.RotateFlower;
import com.yiwan.app.preventionsis.view.RotateFlower.OnClickListener;

import java.io.IOException;

public class MainActivity extends FrameActivity {

    private static final int MSG_INIT_RES_SUCCESS = 98;
    private static final int MSG_INIT_RES_FAIL = 99;
    private static final int MSG_LOAD_RES_SUCCESS = 100;
    private static final int MSG_LOAD_RES_FAIL = 101;
    private static final int MSG_FINISH = 102;

    /**
     * SharedPreference键，标示第一次启动
     */
    public static final String KEY_FIRSTSTART = "first_start";

    private ImageView jie;
    //private ImageView leaves;

    private int screenRotation = 0;

    private AnimationDrawable animationDrawable;
    private CustomProgressDialog dialog;

    private long exitTime = 0;

    private RotateFlower rotateFlower = null;
    private FloatImageView floatImg = null;

    private boolean clickable = true;

    private Handler mUIHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_INIT_RES_FAIL:
                    sendEmptyMessageDelayed(MSG_FINISH, 1000);
                    Toast.makeText(MainActivity.this, "资源初始化错误，请重新安装应用", Toast.LENGTH_SHORT).show();
                    break;
                case MSG_INIT_RES_SUCCESS:
                    PreferencesUtils.setParamDefault(MainActivity.this, KEY_FIRSTSTART, false);
                    loadRes();
                    dialog.dismiss();
                    break;
                case MSG_LOAD_RES_SUCCESS:
                    UpdateManager.getInstance(getApplicationContext()).checkUpdate();
                    LogUtil.d("device token: " + UmengRegistrar.getRegistrationId(MainActivity.this));
                    break;
                case MSG_LOAD_RES_FAIL:
                    sendEmptyMessageDelayed(MSG_FINISH, 1000);
                    Toast.makeText(MainActivity.this, "资源加载错误，请重新安装应用", Toast.LENGTH_SHORT).show();
                    break;
                case MSG_FINISH:
                    finish();
                    break;
            }
        }
    };

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    private void loadRes(){
        final ImageResManager imageResManager = ImageResManager.getInstance();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    int newResVersionCode = imageResManager.loadRes();
                    int appResVersionCode = Integer.parseInt(getResources().getString(R.string.res_version_code));
                    if(newResVersionCode >= appResVersionCode){
                        mUIHandler.sendEmptyMessageDelayed(MSG_LOAD_RES_SUCCESS, 1000);
                    } else {
                        LogUtil.e("res version " + newResVersionCode + " not match current app version " + appResVersionCode);
                        mUIHandler.sendEmptyMessage(MSG_LOAD_RES_FAIL);
                    }
                } catch (IOException e) {
                    LogUtil.e(e);
                    mUIHandler.sendEmptyMessage(MSG_LOAD_RES_FAIL);
                }
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        if (hasFocus)
            //rotateFlower.restartRotate();
            super.onWindowFocusChanged(hasFocus);
    }

    @Override
    protected void onResume() {
        clickable = true;
        if (screenRotation == AppConfig.LANDSCAPE &&
                getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    /**
     * ���ش��?���¼�
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public int getRootView() {
        return R.layout.activity_main_landscape;
    }

    @Override
    public void initView() {
        jie = (ImageView) findViewById(R.id.salute);
        floatImg = (FloatImageView) findViewById(R.id.float_txt);
        rotateFlower = (RotateFlower) findViewById(R.id.rotate_flower);
    }

    @Override
    public void initData() {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        PushAgent mPushAgent = PushAgent.getInstance(this);
        mPushAgent.enable();

        jie.setImageResource(R.drawable.salute);
        animationDrawable = (AnimationDrawable) jie.getDrawable();

        clickable = true;

        rotateFlower.setOnClickListener(new OnClickListener() {
            @Override
            public void onLeavesClicked(final int index) {
                if (!clickable) {
                    return;
                }

                if (animationDrawable.isRunning()) {
//					Log.d("onclick", "animationDrawable.restart");
                    animationDrawable.stop();
                    animationDrawable.start();
                } else {
//					Log.d("onclick", "animationDrawable.start");
                    animationDrawable.start();
                }
                clickable = false;
                int duration = 0;
                for (int i = 0; i < animationDrawable.getNumberOfFrames(); i++) {
                    duration += animationDrawable.getDuration(i);
                }
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    public void run() {
                        Intent intent = new Intent(MainActivity.this, ShowActivity.class);
                        intent.putExtra(AppConfig.INTNET_SHOW_TYPE, index + 1);
                        startActivity(intent);
                    }
                }, duration);
            }

            @Override
            public void onHeartClicked() {
                if (!clickable) {
                    return;
                }
                if (animationDrawable.isRunning()) {
//					Log.d("onclick", "animationDrawable.restart");
                    animationDrawable.stop();
                    animationDrawable.start();
                } else {
//					Log.d("onclick", "animationDrawable.start");
                    animationDrawable.start();
                }
                clickable = false;
                int duration = 0;
                for (int i = 0; i < animationDrawable.getNumberOfFrames(); i++) {
                    duration += animationDrawable.getDuration(i);
                }
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    public void run() {
                        Intent intent = new Intent(MainActivity.this, ShowActivity.class);
                        intent.putExtra(AppConfig.INTNET_SHOW_TYPE, 0);
                        startActivity(intent);
                    }
                }, duration);
            }
        });
        boolean isFirstIn = (boolean) PreferencesUtils.getParamDefault(this, KEY_FIRSTSTART, true);
        boolean shouldUpdate = false;
        if(isFirstIn){
            LogUtil.d("first start, need init res");
            shouldUpdate = true;
        } else {
            try {
                int oldResVersion = ImageResManager.getInstance().getResVersion();
                int newResVersion = Integer.parseInt(getString(R.string.res_version_code));
                if(oldResVersion > newResVersion){
                    LogUtil.d("res version checked, is in latest version " + newResVersion);
                    if(GlobalCfg.DEBUG_MODE){
                        Toast.makeText(mContext, "load res", Toast.LENGTH_SHORT).show();
                    }
                    loadRes();
                    shouldUpdate = false;
                } else {
                    LogUtil.d("res version checked, is not in latest version " + oldResVersion + "=>" + newResVersion);
                    shouldUpdate = true;
                }
            } catch (IOException e) {
                LogUtil.e(e);
                mUIHandler.sendEmptyMessage(MSG_LOAD_RES_FAIL);
            }
        }
        if(shouldUpdate){
            dialog = CustomProgressDialog.createDialog(this);
            dialog.setMessage("初始化资源中...");
            dialog.setCancelable(false);
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();
            Thread thread = new Thread(){
                @Override
                public void run() {
                    try {
                        ImageResManager imageResManager = ImageResManager.getInstance();
                        imageResManager.initRes();
                        mUIHandler.sendEmptyMessage(MSG_INIT_RES_SUCCESS);
                    } catch (IOException e){
                        LogUtil.e(e);
                        mUIHandler.sendEmptyMessage(MSG_INIT_RES_FAIL);
                    }
                }
            };
            thread.start();
        }
    }
}
